import { Plugin } from "vite";
import * as fs from 'fs';
import * as resolve from "resolve";
import { transform } from '@svgr/core'
import path from "path"
interface SvgrOptions {
  defaultExport: 'url' | 'component';
}
export default function viteSvgrPlugin(options: SvgrOptions = { defaultExport: 'component' }) {
  const { defaultExport } = options;
  return {
    name: "vite-plugin-svgr",
    async transform(code: any, id: any) {

      if (!id.endsWith('.svg')) {
        return code;
      }




      const esbuildPackagePath = (resolve as any).sync('esbuild', { basedir: require.resolve("vite") })
      // console.log(esbuildPackagePath);
      const esbuild = require(esbuildPackagePath);
      if (id.startsWith('/') || /^[A-Z]:\\/.test(id)) {
        id = path.posix.join(process.cwd(), "/public", id).replace(/\\/g, "/");

      }
      const svg = await fs.promises.readFile(id, 'utf-8')
      let svgrResult = `export default function Test() {
  console.log("test");
  return <>${svg}</>;
}
`


      let componentCode = svgrResult;
      // if (defaultExport === "url") {
      //   componentCode += code;
      //   componentCode = componentCode.replace('export default ReactComponent', 'export { ReactComponent }');
      // }


      const result = await esbuild.transform(svgrResult, {
        loader: "jsx",
      });
      console.log(result)
      // // console.log("result", result)
      // // console.log(componentCode)
      return {
        code: result.code,
        map: null
      }
    },
  }
}